#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
Created on 2011-05-11

@author: wirenth
'''
import sys
import stompy
import pickle
import base64
import logging
from threading import Thread
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler


log = logging.getLogger("")


# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)


class Reader(Thread):
    def __init__ (self, index, host):
        Thread.__init__(self)

        self.MAX_MESSAGES = 1000
        self.__data_keeper = []
        self.__index = index
        self.__counter = 0
        self.__host = host

    def dump(self):
        return pickle.dumps(self.__data_keeper)

    def load(self, data):
        data_list = pickle.loads(data)
        self.__data_keeper.extend(data_list)

    def run(self):
        self.__get_messages()

    def last(self, n):
        data = pickle.dumps(self.__data_keeper[:n])
        encoded = base64.encodestring(data)
        return encoded

    def __get_messages(self):
        client = stompy.simple.Client(self.__host, 61613) #move to configuration
        client.connect()
        client.subscribe(self.__index)
        while True :
            try:
                log.info("Awaiting message (stored: %d)..." % len(self.__data_keeper))
                msg = client.get()
            except (stompy.simple.Empty):
                log.info("empty")
                time.sleep(100)
		client = stompy.simple.Client(self.__host, 61613)
                client.connect()
                client.subscribe(self.__index)
		continue
            except (stompy.frame.UnknownBrokerResponseError):
                log.info("unknown response")
		continue
            else:
                self.__counter += 1
                log.info("Update received (%d)." % self.__counter)
                self.__data_keeper.insert(0, msg.body)
                if len(self.__data_keeper) > self.MAX_MESSAGES:
                    self.__data_keeper.pop()


def main():
    if len(sys.argv) < 3:
        print "Usage: %s topic port" % sys.argv[0]
        return

    host = sys.argv[2]
    port = int(sys.argv[3])
    index = "jms.topic.%s" % sys.argv[1]

    FORMAT = ("[%s] " % index) + "%(levelname)-15s %(message)s"
    logging.basicConfig(level=logging.INFO, format=FORMAT)

    log.info("Starting reader...")

    data = None
    try:
        with open("%s.dat" % index) as fp:
            data = fp.read()
    except IOError, e:
        log.warning("Loading state error: %s" % e)

    reader = Reader(index, host)
    reader.daemon = True
    if data:
        reader.load(data)
    reader.start()

    log.info("Starting service...")
    server = SimpleXMLRPCServer((host, port), #move to configuration
                            requestHandler=RequestHandler)
    server.register_introspection_functions()
    server.register_function(reader.last, 'last')

    log.info("Serving...")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        log.info("Saving state...")
        with open("%s.dat" % index, "w") as fp:
            fp.write(reader.dump())
        log.info("Bye bye!")


if __name__ == '__main__':
    main()

